import baseUrl from "./url.js"
import store from "../store/index.js"
const request = (url, method, data, contentType = "application/json") => {
	console.log("baseUrl", baseUrl.name, baseUrl.url)
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync("token") || ""
		const httpDefaultOpts = {
			url: baseUrl.url + url,
			data,
			method: method,
			dataType: "json",
			header: {
				"x-requested-with": "XMLHttpRequest",
				"content-type": contentType,
				"Authorization": token,
				"tenant-id": 162,
				"terminal": 31
			}
		} 
		uni.request(httpDefaultOpts).then(res => {
			if (res.statusCode === 200) {
				if(res.data.code === 0) {  //请求成功
					resolve(res.data)
				} else if (res.data.code === -2) {  //token失效
					uni.removeStorageSync("token")
					store.state.isLogin = false
					uni.navigateTo({
						url: '../login/login'
					})							
				} else {
					console.log("发生错误的URL", url, data, res.data)
					resolve(res.data)
				}
			} else {
				console.log("发生错误的URL", url, data)
				reject(res)
			}
		}).catch((response) => {
			console.log("发生错误的URL", url, data, res.data)
			reject(response)			
		})
	})
}

export default request